/**
 * Created by u-fan on 2016/7/10.
 */
!function ($) {
    var defaultSetting = {
        mod:"default",   //默认轮播方式
        active:0,       //当前页
        speed:600,		//速度
        stamp:5,		//切换间隔，为0时不自动切换，单位秒
        showArrow:true, //是否显示左右切换按钮
        pointBar:".point-bar",
        leftArrow:".slider-prev",
        rightArrow:".slider-next",
        onChange:function (idx) {} //切换事件回调
    };
    var isTransform = (function () {
        return !($('<div>').css("transform") === undefined)
    }());

    //定义插件接口
    function Plugin(el, option) {
        option = option || {};
        this.el = $(el);
        this.setting = $.extend({}, defaultSetting, option);
        
        this.$pointBar = option.pointBar?$(option.pointBar): this.el.find(defaultSetting.pointBar);
        this.$leftArrow = option.leftArrow?$(option.leftArrow): this.el.find(defaultSetting.leftArrow);
        this.$rightArrow = option.rightArrow?$(option.rightArrow): this.el.find(defaultSetting.rightArrow);

        $.extend(this, mods[this.setting.mod]);

        this.init();
        this.eventBind();
        this.go(0);
    }

    //添加通用方法
    $.extend(Plugin.prototype, {
        go: function (idx) {
            var side,
                s = this.setting,
                num = this.num;
            if (isNaN(idx) || idx < 0) { //idx为空下一页，-1上一页
                side = isNaN(idx) ? 1 : -1;
                idx = (s.active + side + num) % num;
            } else {
                side = (idx >= s.active) ? 1 : -1;
            }
            this.move(idx, side);
            if (s.stamp) this.autoPlay();
            this.onChange(idx);
        },
        goPre: function () {
            this.go(-1);
        },
        onChange:function (idx) {
            this.$pointBar.children(":eq(" + idx + "),.active").toggleClass("active");
            this.setting.active = idx;
            this.setting.onChange(idx);
        },
        autoPlay: function () {
            var self = this;
            clearTimeout(this.play);
            this.play = setTimeout(function () {
                self.go()
            }, this.setting.stamp * 1000)
        },
        eventBind: function () {
            var self = this,
                s = this.setting;
            //生成焦点绑定事件；
            if (this.$pointBar.size()>0){
                var $points =this.$pointBar.children();
                //生成默认point
                if($points.length<=0){
                    var point="";
                    for(var i=0;i<this.num;i++){
                        point+='<span class="item" data-idx="'+i+'"></span>';
                    }
                    $points = $(point).appendTo(this.$pointBar);
                }
                $points.click(function(){
                    if (!$(this).hasClass("active")){
                        self.go($(this).data("idx"));
                    }
                    return false;
                });
            }
            if (s.showArrow){
                if(this.$leftArrow.length==0){
                    this.$leftArrow = $('<div class="'+ s.leftArrow.substr(1)+' bg-trans">&lt; </div>');
                    this.$rightArrow = $('<div class="'+ s.rightArrow.substr(1)+' bg-trans">&gt; </div>');
                    this.el.append(this.$leftArrow ).append(this.$rightArrow);
                }
                this.$leftArrow.click(function(){self.goPre()});
                this.$rightArrow.click(function(){self.go()});
            }
        }
    });

    var mods = {
        //全副轮播切换；
        'default': {
            init: function () {
                var el = this.el;
                this.$items = el.find(".slider-item");
                this.num = this.$items.size();
                this.viewWidth = el.width();
                if (el.height() == 0) { //没有定义可视高度时，填充高度
                    if (this.$items.height()) {
                        el.height(this.$items.height());
                    } else {
                        this.$items.find("img").eq(0).one("load", function () {
                            el.height(this.height);
                        });
                    }
                }
            },
            move: function (idx, side) {//side为1或-1；表示运动方向1为向左滚动至下一张，-1为向右滚动上一张
                var $items = this.$items,
                    s = this.setting,
                    around = (side == 1) ? "left" : "right",
                    dir = (side == 1) ? "next" : "pre";
                var idxItem = $items.eq(idx).addClass(dir);
                idxItem[0].offsetWidth;  //进行一次读操作force reflow
                var moves = idxItem.add($items.eq(s.active)).addClass(around);

                setTimeout(function () {
                    moves.toggleClass("active").removeClass([around, dir].join(' '));
                }, s.speed);
                //不支持CSS动画，调用Jquery动画；
                if (!isTransform) {
                    var viewWidth = this.viewWidth;
                    idxItem.css("left", viewWidth * side);
                    moves.animate({"left": "-=" + viewWidth * side + "px"}, s.speed);
                }
            }
        },
        //步长滚动
        'step': {}
    };
    //注册到jquery插件
    $.fn.slider= function (option) {
        return this.each(function () {
            var $this = $(this);
            if (!$this.data("slider")){
                $this.data("slider",new Plugin(this,option))
            }
        })
    }
    //返回全局的构造函数；
    //创建实例 new Slider(".slider")
    //global.Slider = Plugin;
    //return Plugin;
}(jQuery);